#!/bin/bash

# Copyright (C) 2024 nosignal

neko_status=$(uci -q get neko.cfg.enabled)
neko_new_interface=$(uci -q get neko.cfg.new_interface)
neko_delay=$(uci -q get neko.cfg.delay)
neko_dir="/etc/neko"
tun_bin="$neko_dir/core/tun"
neko_pid="$neko_dir/tmp/neko_pid.txt"
log="$neko_dir/tmp/log.txt"
firewall="/etc/init.d/firewall"
neko_version=$1

neko_reload(){
    echo "Checking New Interfaces."
    dt=`ubus call network.interface dump`
    len=`echo $dt | jq '.interface' | jq length`

    for (( i=0; i<$len; i++ ))
    do
        tmpdt=`echo $dt | jq ".interface[$i]"`
        status=`echo $tmpdt | jq '.up'`
        if [ $status = true ]; then
            iface=`echo $tmpdt | jq '.interface' | sed 's/"//g'`
            uptime=`echo $tmpdt | jq '.uptime'`
            if [ "$iface" == "loopback" -o "$iface" == "lan" ]; then
                echo "Interfaces $iface is whitlisted"
            else
                if [[ ! -d "/tmp/iface" ]]; then
                    echo "creating tmp dir"
                    mkdir /tmp/iface
                fi
        
                if [ ! -e /tmp/iface/$iface ]; then
                    echo $uptime > /tmp/iface/$iface
                    $firewall restart
                    echo "[ `date +%T` ] - Detected interfaces $iface changed, Reloading Firewall " >> $log
                    $tun_bin -ks
                    uptime_now=`cat /proc/uptime | cut -d. -f1`
                    if [ "$uptime_now" -lt 60 ]; then
                        service neko restart
                    fi
                fi

                last_uptime=`cat /tmp/iface/$iface`
                echo $uptime > /tmp/iface/$iface
                echo "- $iface Uptime $uptime s, last Uptime $last_uptime s"

                if (( $uptime < $last_uptime )) || [ -z $last_uptime ]; then
                    echo "reloading firewall"
                    $firewall restart
                    echo "[ `date +%T` ] - Detected interfaces $iface changed, Reloading Firewall " >> $log
                    sleep 1
                    $tun_bin -ks
                else
                    echo "nothing"
                fi
            fi
        fi
    done
}

if [ "$neko_status" == 1 ] && [ "$neko_new_interface" == 1 ]; then
    echo "[ `date +%T` ] - Auto Restart Firewall : ON " >> $log
    cnt=0;
    while true
    do
        ((cnt++))
        sleep "$neko_delay"
        neko_reload
        if [ $cnt == 30 ]; then
            neko_checknewver "log"
        fi
    done
else
    echo "[ `date +%T` ] - Auto Restart Firewall : OFF " >> $log
    sleep 20 && neko_checknewver "log"
fi